% Bootstrap rating history : 2008 sub-sample C
% Built connection between R and Matlab through package of Matlab Rlink. 
% Using RAndFriends on http://rcom.univie.ac.at/download.html, we install statconnDCOM.
% 
% Taking rating history of 2008 group C, we convert dataframe format into matrix 
% which is readable for Matlab. Date serial number calculation is different for
% R (start from 1970-1-1) and Matlab (0000-1-1). 
% 
% Data is now imported into Matlab and bootstrap start.
% 
% Bootstrap finish.  The replication export to R with format convert to dataframe.

clc
clear all

%% Import data from R to Matlab

status = openR;
evalR('load("D:\\My Documents\\R\\RResult\\Q_ML_grp4_01_WRcensor_8states.RData")')
evalR('mat <- matrix(unlist(newdata_4), ncol=5)') 
data = getRdata('mat');
data(:,2)= data(:,2)+datenum('1-Jan-1970');
data(:,4) = []; % removes the 2nd column
closeR;

%% Sampling with replacement to create a new data set

% Generate an index
customer = data(:,1);
lengthCus = length(customer);
cusDistinct = unique(customer);

% Use the index to create a new dataset
REP = 1000;
bootDataSize = zeros(REP,1);
tic;
for j = 1: REP % replication REP times
    boot_index = randsample(cusDistinct,length(cusDistinct), 'true');
    
    bootData = [];
    for i = 1: length(boot_index)
        row = find(customer == boot_index(i));
        rowdata = data(row,2:size(data,2));
        b = i * ones(length(row), 1); 
        b(:,2:4) = rowdata;
        bootData = [bootData; b];        
        clear row rowdata b

%         if length(bootData)>= lengthCus 
%             break 
%         end    
    end
    bootDataSize(j) = length(bootData);
    msg = ['boots_data',num2str(j),' Size ', num2str(bootDataSize(j))];
    disp (msg);
     
    savefile = strcat('D:\My Documents\CIRANO\db_mySQL\bootstrap_01\boot_', num2str(j),'.mat');
    save(savefile,'bootData');
    clear boot_index bootData 
end

toc



%% Export data to R
%newdata.df<-as.data.frame(a[1:10,1:3]) 